<!-- src/components/class-center/StudentManagement.vue -->
<template>
  <div class="student-management">
    <!-- 筛选区域 -->
    <div class="filter-section">
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="filter-item">
            <span class="filter-label">学期：</span>
            <el-select
                v-model="filters.termId"
                placeholder="请选择学期"
                clearable
            >
              <el-option
                  v-for="item in termOptions"
                  :key="item.termId"
                  :label="item.termName"
                  :value="item.termId"
              />
            </el-select>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="filter-item">
            <span class="filter-label">年级：</span>
            <el-select
                v-model="filters.gradeLevel"
                placeholder="请选择年级"
                clearable
            >
              <el-option
                  v-for="item in gradeOptions"
                  :key="item"
                  :label="item"
                  :value="item"
              />
            </el-select>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="filter-item">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 学生表格 -->
    <el-table
        :data="studentList"
        stripe
        style="width: 100%"
        v-loading="loading"
    >
      <el-table-column prop="name" label="学生姓名" />
      <el-table-column prop="studentId" label="学号" />
      <el-table-column prop="averageScore" label="平均分" align="center">
        <template #default="{ row }">
          <el-tag :type="getScoreTagType(row.averageScore)">
            {{ row.averageScore }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="attendanceRate" label="实践活动出勤率" align="center">
        <template #default="{ row }">
          <el-progress
              :percentage="row.attendanceRate"
              :color="getAttendanceColor(row.attendanceRate)"
              :show-text="false"
          />
          <span style="margin-left: 8px">{{ row.attendanceRate }}%</span>
        </template>
      </el-table-column>
      <el-table-column prop="honorEvaluation" label="荣誉评价">
        <template #default="{ row }">
          <el-tag :type="getHonorTagType(row.honorEvaluation)">
            {{ getHonorLabel(row.honorEvaluation) }}
          </el-tag>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container" v-if="pagination.total > pagination.pageSize">
      <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, defineProps } from 'vue'
import { ElMessage } from 'element-plus'
import { fetchAllTermsForStudents, fetchAllGrades, fetchStudentsByCriteria } from '@/api/teacher'

interface StudentItem {
  id: number
  username: string
  name: string
  role: string
  studentId: string
  gradeLevel: string
  className: string
  averageScore: number
  attendanceRate: number
  honorEvaluation: string
}

interface TermOption {
  termId: number
  termName: string
  startDate: string
  endDate: string
  isCurrent: boolean
}

interface Filters {
  termId: number | null
  gradeLevel: string
}

interface Pagination {
  currentPage: number
  pageSize: number
  total: number
}

// Props
const props = defineProps<{
  teacherId: number
}>()

// 响应式数据
const loading = ref(false)
const studentList = ref<StudentItem[]>([])
const termOptions = ref<TermOption[]>([])
const gradeOptions = ref<string[]>([])

const filters = reactive<Filters>({
  termId: null,
  gradeLevel: ''
})

const pagination = reactive<Pagination>({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 荣誉评价选项
const honorOptions = [
  { value: 'excellent', label: '优秀' },
  { value: 'good', label: '良好' },
  { value: 'average', label: '一般' },
  { value: 'poor', label: '待改进' }
]

// 方法
const getScoreTagType = (score: number) => {
  return 'primary'
}

const getAttendanceColor = (rate: number) => {
  return '#409EFF'
}

const getHonorTagType = (evaluation: string) => {
  return 'primary'
}

const getHonorLabel = (value: string) => {
  return honorOptions.find(opt => opt.value === value)?.label || value
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadStudentList()
}

const handleReset = () => {
  filters.termId = null
  filters.gradeLevel = ''
  handleSearch()
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  loadStudentList()
}

const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  loadStudentList()
}

// 加载学期选项
const loadTermOptions = async () => {
  try {
    const response = await fetchAllTermsForStudents()
    if (response.success) {
      termOptions.value = response.data
    } else {
      ElMessage.error(response.message || '加载学期选项失败')
    }
  } catch (error) {
    console.error('加载学期选项失败:', error)
    ElMessage.error('加载学期选项失败')
  }
}

// 加载年级选项
const loadGradeOptions = async () => {
  try {
    const response = await fetchAllGrades()
    if (response.success) {
      gradeOptions.value = response.data
    } else {
      ElMessage.error(response.message || '加载年级选项失败')
    }
  } catch (error) {
    console.error('加载年级选项失败:', error)
    ElMessage.error('加载年级选项失败')
  }
}

// 加载学生列表
const loadStudentList = async () => {
  loading.value = true
  try {
    const response = await fetchStudentsByCriteria(
        props.teacherId,
        filters.termId || undefined,
        filters.gradeLevel || undefined
    )

    if (response.success) {
      studentList.value = response.data
      pagination.total = studentList.value.length
    } else {
      ElMessage.error(response.message || '获取学生列表失败')
    }
  } catch (error) {
    console.error('加载学生列表失败:', error)
    ElMessage.error('加载学生列表失败')
  } finally {
    loading.value = false
  }
}

// 初始化加载
const initData = async () => {
  await Promise.all([
    loadTermOptions(),
    loadGradeOptions(),
    loadStudentList()
  ])
}

// 生命周期
onMounted(() => {
  initData()
})
</script>

<style scoped>
.student-management {
  padding: 0;
}

.filter-section {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #ffffff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.filter-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.filter-label {
  width: 60px;
  text-align: right;
  margin-right: 10px;
  font-weight: 500;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

:deep(.el-table .cell) {
  text-align: center;
}

:deep(.el-table th > .cell) {
  font-weight: 600;
}
</style>
